import {Component, OnInit, ViewChild} from '@angular/core';
import { Observable } from 'rxjs';
declare let RTCPeerConnection: any;


@Component({
  selector: 'app-meeting',
  templateUrl: './meeting.component.html',
  styleUrls: ['./meeting.component.css']
})
export class MeetingComponent implements OnInit {

  callActive: boolean = false;
  pc: any;
  localStream: any;
  senderId: string |undefined;

  @ViewChild("me") me: any;
  @ViewChild("remote") remote:any;


  constructor() { }

  ngOnInit(): void {

//this.setUpWebRtc();
  }



  setUpWebRtc(){


    try {
      this.pc = new RTCPeerConnection();
    } catch (e) {
      console.dir(e);
    }

    this.pc.onicecandidate = (event:any)=>{
      if(event.candidate){
        console.log("捕获到iceCandidate");
      }
    }

    this.pc.onremovestream =(event:any)=>{
      console.log("Catch Remove Stream")
    }

    this.pc.ontrack = (event:any)=>{
      console.log("捕获到Tracks");
      this.remote.nativeElement.srcObject=event.streams[0];
      // ？
      //this.showMe()
    }
    this.showMe();
    console.dir(this.pc);

  }



  showMe(){
   navigator.mediaDevices.getUserMedia({audio:true,video:true})
     .then((stream:any)=>{
       this.me.nativeElement.srcObject=stream;

       this.pc.addStream(stream);
       this.localStream=stream;
       //this.pc.addtrack(this.localStream);
     });
  }


  showRemote(){
    try {
      this.pc.createOffer()
        .then((offer: any) => {
          this.pc.setLocalDescription(offer);
          //将SDP发送到服务器
          //this.sendMessage(this.senderId, JSON.stringify({ sdp: this.pc.localDescription }));
        });
    } catch (e) {
      console.dir(e);

    }
  }


  hangup(){
    this.pc.close();
    let tracks=this.localStream.getTracks();
    for(let i=0;i<tracks.length;i++){
      tracks[i].stop();
    }

  }

}
